package com.kx.hackathon.service.impl;


import com.kx.hackathon.service.HandlerService;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;

@Service("TianQiYuBaoServiceImpl")
public class TianQiYuBaoServiceImpl implements HandlerService {


    @Override
    public String handle(String msg, String arg) throws Exception {
        if(arg==null || arg.equals("")){
            return "你不得告诉我要查哪个城市的天气啊？";
        }
        //请求地址设置
        String url = "https://api.apishop.net/common/weather/get24HoursWeatherByArea";
        //请求方法设置
        String requestMethod = "POST";
        //请求头部设置
        Map<String, String> headers = new HashMap<String, String>();
        //请求参数设置
        Map<String, String> params = new HashMap<String, String>();
        params.put("apiKey", "cqWYjN99ba4f5b165e2cfdf0740d21f62c35913b5264591");
        params.put("area", arg);
//        params.put("areaID", "参数3");
        String result = proxyToDesURL(requestMethod, url, headers, params);
        if (result != null) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String status_code = jsonObject.getString("statusCode");
            if (status_code.equals("000000")) {
                // 状态码为000000, 说明请求成功
                System.out.println("请求成功：" + jsonObject.getString("result"));
                result = jsonObject.getString("result");
                jsonObject = JSONObject.parseObject(result);
                result = jsonObject.getString("hourList");
                String[] splits = result.split("}");
                result = splits[0];
                result = result.replaceAll("\"area\"","地区");
                result = result.replaceAll("\"temperature\"","温度");
                result = result.replaceAll("\"weather\"","天气状况");
                result = result.replaceAll("\"wind_direction\"","风向");
                result = result.replaceAll("\"time\"","时间");
                result = result.replaceAll("\"wind_power\"","风力");
                result = result.substring(2);
                String[] strings = result.split(",");
                Date nowdate = new Date();
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(format1);
                strings[5] = "时间:"+"\""+format1.format(nowdate).toString()+"\"";
                result = strings[0]
                        +","+ strings[2]
                        +","+ strings[3]
                        +","+ strings[4]
                        +","+ strings[5]
                        +","+ strings[7];
                result = result.replaceAll("\"","");
            } else {
                // 状态码非000000, 说明请求失败
                System.out.println("请求失败：" + jsonObject.getString("desc"));
                return "哎呀，没查到，可能是你没充钱！";
            }
        } else {
            // 返回内容异常，发送请求失败，以下可根据业务逻辑自行修改
            System.out.println("发送请求失败");
            return "哎呀，没查到，可能是你没充钱！";
        }
        return result;
    }

    @Override
    public String init(String msg, String arg) {
        return null;
    }

    @Override
    public boolean needInit() {
        return false;
    }

    /**
     * 请求接口
     * @param method 请求方法
     * @param url 请求地址
     * @param headers 请求头部
     * @param params 请求参数
     * @return
     */
    public static String proxyToDesURL(String method, String url, Map<String, String> headers,
                                       Map<String, String> params) {
        // TODO Auto-generated method stub
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            //处理请求头部
            HttpHeaders requestHeaders = new HttpHeaders();
            if (headers != null && !headers.isEmpty()) {
                Set<String> set = headers.keySet();
                for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
                    String key = iterator.next();
                    String value = headers.get(key);
                    requestHeaders.add(key, value);
                }
            }
            //处理请求参数
            MultiValueMap<String, String> paramList = new LinkedMultiValueMap<String, String>();
            if (params != null && !params.isEmpty()) {
                if(method.equalsIgnoreCase("GET"))
                {
                    url += "?";
                    Set<String> set = params.keySet();
                    for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
                        String key = iterator.next();
                        String value = params.get(key);
                        url += key+"="+value+"&";
                    }
                    url = url.substring(0, url.length() - 1);
                }
                else
                {
                    Set<String> set = params.keySet();
                    for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
                        String key = iterator.next();
                        String value = params.get(key);
                        paramList.add(key, value);
                    }
                }
            }
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                    paramList, requestHeaders);
            //处理请求方法
            HttpMethod requestType = HttpMethod.GET;
            method = method.toUpperCase();
            switch (method) {
                case "GET":
                    requestType = HttpMethod.GET;
                    break;
                case "POST":
                    requestType = HttpMethod.POST;
                    break;
                case "PUT":
                    requestType = HttpMethod.PUT;
                    break;
                case "DELETE":
                    requestType = HttpMethod.DELETE;
                    break;
                case "HEAD":
                    requestType = HttpMethod.HEAD;
                    break;
                case "OPTIONS":
                    requestType = HttpMethod.OPTIONS;
                    break;
                default:
                    requestType = HttpMethod.GET;
                    break;
            }
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, requestType, requestEntity,
                    String.class, params);
            //获取返回结果
            return responseEntity.getBody();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}
